package com.ejuornal.dao.impl;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Component;

import com.ejuornal.bean.Subscribe;
import com.ejuornal.dao.SubscribeDao;

/**
 * 订阅
 * @author 石亚博
 */
@Component("subscribeDao")
public class SubscribeDaoImpl extends DaoSupport<Subscribe> implements
		SubscribeDao {

	public void add(String sql, Object... objs) {
		super.add(sql, objs);
	}

	public void batchDelete(String sql, int... ids) {
		super.batchDelete(sql, ids);
	}

	public Subscribe findById(int subscribeId) {
		String sql = "SELECT * FROM t_subscribe WHERE subscribeId = ?";
		Subscribe subscribe = super.getJdbcTemplate().queryForObject(sql,
				new Object[] { subscribeId }, new RowMapper<Subscribe>() {

					public Subscribe mapRow(ResultSet rs, int roeNum)
							throws SQLException {
						Subscribe subscribe = new Subscribe();
						subscribe.setSubscribeId(rs.getInt("subscribeId"));
						subscribe.setUserId(rs.getInt("userId"));
						subscribe.setPeriodicalId(rs.getInt("periodicalId"));

						return subscribe;
					}
				});

		return subscribe;
	}

	@Override
	public void cancelSubscribe(int periodicalId, int userId) {
		String sql = " DELETE  FROM  t_subscribe  WHERE  t_subscribe.periodicalId  = ? AND  t_subscribe.userId = ?  ";
		getJdbcTemplate().update(sql, new Object[]{periodicalId , userId});
	}

	@Override
	public List<String> findByListPeriodicalId(int periodicalId) {
		String sql = "select email from t_user where userId in (select userId from t_subscribe where periodicalId=?)";
		List<String> strs = getJdbcTemplate().queryForList(sql, new Object[]{periodicalId}, String.class);
		return strs;
	}

	@Override
	public int isSubscribe(int userId, int periodicalId) {
		String sql = "SELECT COUNT(*) FROM (SELECT periodicalId FROM t_subscribe WHERE userId=?) AS sub WHERE sub.periodicalId=?";
		@SuppressWarnings("deprecation")
		int result = super.getJdbcTemplate().queryForInt(sql, new Object[]{ userId, periodicalId });
		return result;
	}
}
